﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using System.IO;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Linq;

namespace RandomListItem.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        #region Private/Protected Methodes
        /// <summary>
        /// Prüft ob eine Sharepoint Liste existiert
        /// </summary>
        /// <param name="strListName"></param>
        /// <returns></returns>
        private bool ListExists(string strListName)
        {
            bool exists = false;

            using (SPSite objSPSite = new SPSite(VisualWebPart1._siteUrl))
            {
                using (SPWeb objSPWeb = objSPSite.OpenWeb())
                {
                    if (objSPWeb.Lists.TryGetList(strListName) != null)
                        exists = true;
                }
            }

            return exists;
        }
        /// <summary>
        /// Zählt die Anzahl an Listenelementen
        /// </summary>
        /// <param name="strListName"></param>
        /// <returns></returns>
        private int ItemCount(string strListName)
        {
            int result = 0;

            using (SPSite objSPSite = new SPSite(VisualWebPart1._siteUrl))
            {
                using (SPWeb objSPWeb = objSPSite.OpenWeb())
                {
                    SPList objSPList = objSPWeb.Lists.TryGetList(strListName);

                    if (objSPList != null)
                    {
                        result = objSPList.ItemCount;
                    }
                }
            }

            return result;
        }
        /// <summary>
        /// Erzeugt eine Zufallszahl
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        private int RandomNumber(int min, int max)
        {
            Random random = new Random();
            return random.Next(min, max);
        }
        /// <summary>
        /// Gibt das gewünschte Listenelement zurück
        /// </summary>
        /// <param name="strListName"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private SPListItem GetListItem(string strListName, int value)
        {
            SPListItem item = null;
            using (SPSite objSPSite = new SPSite(VisualWebPart1._siteUrl))
            {
                using (SPWeb objSPWeb = objSPSite.OpenWeb())
                {
                    SPList objSPList = objSPWeb.Lists.TryGetList(strListName);

                    if (objSPList != null)
                    {
                        item = objSPList.Items[(value - 1)];
                    }
                }
            }

            return item;
        }
        /// <summary>
        /// Prüft ob alle notwendigen Informationen im Eigenschaftenfenster eingetragen wurden
        /// </summary>
        /// <returns></returns>
        private bool CheckCustomFields()
        {
            bool result = true;

            if ((VisualWebPart1._siteUrl == null) || (VisualWebPart1._siteUrl.Equals(String.Empty)))
            {
                this.LabelError.Text = "Es wurde keine Website eingestellt<br>Bitte wechseln Sie in die Webpart-Eigenschaften und hinterlegen Sie eine gültige Website-Adresse";
                result = false;
            }
            else if ((VisualWebPart1._listTitle == null) || (VisualWebPart1._listTitle.Equals(String.Empty)))
            {
                this.LabelError.Text = "Es wurde kein Listenname hinterlegt<br>Bitte wechseln Sie in die Webpart-Eigenschaften und hinterlegen Sie einen gültigen Listennamen";
                result = false;
            }
            else if ((VisualWebPart1._titleField == null) || (VisualWebPart1._titleField.Equals(String.Empty)))
            {
                this.LabelError.Text = "Es wurde kein Titelfeld hinterlegt<br>Bitte wechseln Sie in die Webpart-Eigenschaften und hinterlegen Sie ein gültiges Titelfeld";
                result = false;
            }
            else if ((VisualWebPart1._tooltipField == null) || (VisualWebPart1._tooltipField.Equals(String.Empty)))
            {
                this.LabelError.Text = "Es wurde kein Tooltip-Feld hinterlegt<br>Bitte wechseln Sie in die Webpart-Eigenschaften und hinterlegen Sie ein gültiges Tooltip-Feld";
                result = false;
            }
            return result;
        }
        /// <summary>
        /// Dispaly a random List Item
        /// </summary>
        protected void GenerateView()
        {
            if (!CheckCustomFields())
            {
                this.PanelError.Visible = true;
                this.PanelMain.Visible = false;
            }
            else
            {
                if (ListExists(VisualWebPart1._listTitle))
                {
                    this.PanelError.Visible = false;
                    this.PanelMain.Visible = true;
                    int itemNumber = RandomNumber(1, (ItemCount(VisualWebPart1._listTitle) + 1));
                    SPListItem item = GetListItem(VisualWebPart1._listTitle, itemNumber);

                    if (item != null)
                    {
                        string url = VisualWebPart1._siteUrl + item.ParentList.DefaultDisplayFormUrl + "?ID=" + item.ID.ToString();
                        this.HyperLink1.ToolTip = item[VisualWebPart1._tooltipField].ToString();
                        this.HyperLink1.Text = item[VisualWebPart1._titleField].ToString();
                        this.HyperLink1.NavigateUrl = url;

                        this.HyperLink2.NavigateUrl = VisualWebPart1._siteUrl + item.ParentList.DefaultViewUrl;
                    }
                }
                else
                {
                    this.LabelError.Text = "Die Liste <b>" + VisualWebPart1._listTitle + "</b> wurde nicht auf <b>" + VisualWebPart1._siteUrl + "</b> gefunden";
                    this.PanelError.Visible = true;
                    this.PanelMain.Visible = false;
                }
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                GenerateView();
            }
            catch (Exception ex)
            {
                this.LabelError.Text = "<b>Es ist ein Fehler aufgetreten:</b><br>";
                this.LabelError.Text += ex.GetType() + "<br>";
                this.LabelError.Text += ex.Message;

                this.PanelError.Visible = true;
                this.PanelMain.Visible = false;
            }
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            try
            {
                GenerateView();
            }
            catch (Exception ex)
            {
                this.LabelError.Text = "<b>Es ist ein Fehler aufgetreten:</b><br>";
                this.LabelError.Text += ex.GetType() + "<br>";
                this.LabelError.Text += ex.Message;

                this.PanelError.Visible = true;
                this.PanelMain.Visible = false;
            }
        }
    }
}
